import Mock from 'mockjs'

let list = []
for (let i = 0; i < 30; i++) {
    list.push(
        Mock.mock({
            id: i,
            name: Mock.Random.cname(),
            age: Mock.Random.integer(10, 60),
            sex: Mock.Random.integer(0, 1),
            birth: Mock.Random.date(),
            addr: Mock.Random.region() + Mock.Random.county(true)
        })
    )
}
/**
 * sleep
 * @param numberMillis
 */
function sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}
export default {
    /**
     * 获取User列表
     * @param config
     * @returns {{code: number, count, list}}
     */
    getUserList: config => {
        const { name = '', page = 1, limit = 10 } = JSON.parse(config.body)
        console.log('name:' + name, 'page:' + page, '分页大小limit:' + limit)
        const mockList = list.filter(user => {
            if (name && user.name.indexOf(name) === -1 && user.addr.indexOf(name) === -1) return false
            return true
        })
        const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page -1))
        // sleep(500)
        return {
            code: 200,
            total: mockList.length,
            list: pageList
        }
    },
    /**
     * 修改用户
     * @param config
     * @returns {{code: number}}
     */
    editUser: config => {
        const user = JSON.parse(config.body);
        var index = list.findIndex(item => item.id === user.id);
        list.splice(index, 1, user);
        return {
            code: 200
        }
    },
    /**
     * 新增用户
     * @param config
     * @returns {{code: number}}
     */
    addUser: config => {
        const user = JSON.parse(config.body);
        list.push(user);
        return {
            code: 200
        }
    },
    deleteUser: config => {
        const { id } = JSON.parse(config.body);
        var index = list.findIndex(item => item.id === id);
        list.splice(index, 1)
        return {
            code: 200
        }
    }
}